package cn.jwcat.utils;

import cn.jwcat.entity.Staff;
import cn.jwcat.entity.User;
import cn.jwcat.mapper.StaffMapper;
import cn.jwcat.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * JWT的token，区分大小写
 */
@Data
@Component
@AllArgsConstructor
@NoArgsConstructor
public class JwtTokenUtil {

	@Value("${jwt.secret}")
	String secret;

	@Value("${jwt.expiration}")
	long expire;

	@Value("${jwt.tokenHeader}")
	String header;

	@Resource
	StaffMapper staffMapper;
	@Resource
	UserMapper userMapper;

	/**
	 * 对jwt进行切割，获取真正的token
	 */
	public String getTokenFromRequest(HttpServletRequest request) {
		System.out.println(request.getHeader(header));
		return request.getHeader(header);
	}

	/**
	 * 生成token
	 */
	public String createToken(int id) {
		String subject = String.valueOf(id);
		Date nowDate = new Date();
		Date expireDate = new Date(nowDate.getTime() + expire * 1000);//过期时间
		return Jwts.builder()
			.setHeaderParam("type", "JWT")
			.setSubject(subject)
			.setIssuedAt(nowDate)
			.setExpiration(expireDate)
			.signWith(SignatureAlgorithm.HS512, secret)
			.compact();
	}

	/**
	 * 获取token中注册信息
	 */
	public Claims getTokenClaim(String token) throws ExpiredJwtException {
		try {
			return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 验证token是否过期失效
	 */
	public boolean isTokenExpired(Date expirationTime) {
		return expirationTime.before(new Date());
	}

	/**
	 * 获取token失效时间
	 */
	public Date getExpirationDateFromToken(String token) {
		return getTokenClaim(token).getExpiration();
	}

	/**
	 * 获取用户名从token中
	 */
	public String getIDFromToken(String token) {
		return getTokenClaim(token).getSubject();
	}

	/**
	 * 获取jwt发布时间
	 */
	public Date getIssuedAtDateFromToken(String token) {
		return getTokenClaim(token).getIssuedAt();
	}

	/**
	 * 从request中获取token并根据id得到登录对象
	 */
	public Staff getStaffFromRequest(HttpServletRequest request) {
		String token = getTokenFromRequest(request);
		int id = Integer.parseInt(getIDFromToken(token));
		return staffMapper.selectById(id);
	}

	/**
	 * 从request中获取token并根据id得到登录对象
	 */
	public User getUserInfo(HttpServletRequest request) {
		String token = getTokenFromRequest(request);
		int id = Integer.parseInt(getIDFromToken(token));
		return userMapper.selectById(id);
	}

	/**
	 * 从request中获取token中的id
	 */
	public Integer getIDFromRequest(HttpServletRequest request) {
		String token = getTokenFromRequest(request);
		return Integer.parseInt(getIDFromToken(token));
	}
}